(function( global, factory ) {
	if ( typeof define === "function" && define.amd ) {
		// AMD. Register as an anonymous module.
		define( [ "Vue" ], factory );
	} else if ( typeof module === "object" && module.exports ) {
		// Node/CommonJS
		var Vue = require( "Vue" );
		module.exports = factory( Vue );
	} else {
		factory( global.Vue );
	}
})( this, function( Vue ) { 
	
//console.error = function(){}
//关闭Vue的错误信息和提示
//Vue.config.silent = true;
//忽略自定义元素的校验,Vue 2.5+支持正则.
Vue.config.ignoredElements = [
	/^adui-/
];

Vue.directive('move',{
	bind: function( $el , dir, vNode ){
		function stopBubble(e){
			//一般用在鼠标或键盘事件上
			if(e && e.stopPropagation){
				//W3C取消冒泡事件
			  	e.stopPropagation();
			}else{
			  	//IE取消冒泡事件
			  	e.cancelBubble = true;
			}
	  	};		
		vNode.context.move = {
	      	isMove: false,
	      	left: 0,
	      	top: 0
    	};
		vNode.context.mousedown = function(e){
			stopBubble(e);
		    vNode.context.move.left = e.clientX - $el.offsetLeft;
		    vNode.context.move.top = e.clientY - $el.offsetTop;
		    vNode.context.move.isDown = true;			
		}
		vNode.context.mouseup = function(e){
			stopBubble(e);
			vNode.context.move.isDown = false;			
		}
		vNode.context.mousemove = function(e){
			stopBubble(e);
			if(!vNode.context.move.isDown) return;
			$el.style.position = 'fixed';
			$el.style.left = e.clientX - vNode.context.move.left + "px";
			$el.style.top = e.clientY - vNode.context.move.top + "px";			
		}
		$el.addEventListener('mousedown',vNode.context.mousedown);
		$el.addEventListener('mouseup',vNode.context.mouseup);
		$el.addEventListener('mousemove',vNode.context.mousemove);
	},
	inserted :function(){
		console.log("inserted",arguments);
	},
	update : function(){
		console.log("update",arguments);
	},
	componentUpdated: function(){
		console.log("componentUpdated",arguments);
	},
	unbind: function(){
		console.log("unbind",arguments);
	}
});


//构建Vue的示例
var WindowApp = Vue.extend({
	el : document.createElement('WindowApp'),
	template : document.querySelector('#app_template').innerHTML,
	data : function(){
		return {
			title : "",
			src : "",
			show : true,
			style : "",
			loaded : false
		}
	},
	methods : {
		min : function(){
			this.$el.classList.remove('max');
			this.$el.classList.add('min');
			this.wrapperStyle = "color:red;"
		},
		max : function(){
			this.$el.classList.toggle('max');
			this.$el.classList.remove('min');			
		},
		close : function(){
			this.$el.remove();
		},
		load : function(e){
			console.log(e);
			this.loaded = true;
		},
		error : function(e){
			console.error(e);
			this.loaded = true;
		}
	},
	mounted : function(){
		document.body.appendChild(this.$el);
		this.$iframe = this.$el.querySelector('iframe');
		this.$iframe.addEventListener('load',this.load);
		this.$iframe.addEventListener('error',this.error);			
	},
	beforeDestroy : function(){
		this.$iframe.removeEventListener('laod',this.load);
		this.$iframe.removeEventListener('error',this.error);
	}
});

// 应用状态
WindowApp.status = {
	normal : "normal",
	min  : "min",
	max  : "max",
	close : "close"
};


var TaskStart = Vue.extend({
	el : document.createElement( 'TaskStart' ),
	template : document.querySelector('#taskstart_template').innerHTML,
	data : function(){
		return {
			show : true
		};
	},
	methods : {
		closeTaskView : function(e){
			if(!isMatch( e.target,'adui-taskbar-start,adui-taskstart' )){
				this.show = false;
			}
		},
		defaultClick : function(e){
        	if (e.cancelable) {
	            // 判断默认行为是否已经被禁用
	            if (!e.defaultPrevented) {
	                e.preventDefault();
	            }
	        }
	        e.stopImmediatePropagation();
	        e.stopPropagation();	
	        this.show = true;
		}
	},
	mounted : function(){
		document.body.appendChild(this.$el);
		document.body.addEventListener('click',this.closeTaskView.bind(this));
	},
	destroyed : function(){
		this.$el.remove();
		document.body.removeEventListener('click',this.closeTaskView);
	}
});

var Contextmenu = Vue.extend({
	el : document.createElement('Contextmenu'),
	template : document.querySelector('#contextmenu_template').innerHTML,
	created : function(){
		Contextmenu.cm.forEach(function(cm){
			cm.$destroy()
		});
		Contextmenu.cm.push(this);
	},
	mounted : function(){
		document.body.appendChild(this.$el);
		document.body.addEventListener('contentmenu',this.defaultClick);
		this.$el.addEventListener('click',this.defaultClick);
	},
	destroyed : function(){
		document.body.removeEventListener('contentmenu',this.defaultClick);
		this.$el.removeEventListener('click',this.defaultClick);
		this.$el.remove();
	},
	methods : {
		defaultClick : function(){
			this.$destroy();
		},
		closeContextmenu : function(){
			Contextmenu.cm.forEach(function(cm){
				cm.$destroy()
			});			
		}
	}
});
Contextmenu.cm=[];
document.addEventListener('click',function(e){
	if(!e.target.matches('adui-contextmenu,adui-contextmenu *')){
		Contextmenu.cm.forEach(function(cm){
			cm.$destroy()
		});			
	}
});


var Message = Vue.extend({
	el : document.createElement('Message'),
	template : document.querySelector('#message_template').innerHTML,
	created :function(){
		this.mid = Message.mid++;
	},
	mounted : function(){
		document.body.appendChild(this.$el);
		this.timer = setTimeout(function(){
			this.$destroy();
		}.bind(this),3000);
	},
	destroyed : function(){
		this.$el.remove();
		clearTimeout(this.timer);
	}
});
Message.mid = 1;

function isMatch( dom,selector ){
	if( dom.matches( selector ) ){
		return true;
	}
	if( dom == document.body ){
		return false;
	}
	return isMatch( dom.parentElement,selector );
}

function setStyle( dom, styles ){
	for( var style in styles ){
		( style in dom.style ) && 
		( dom.style[ style ] = styles[ style ] );
	}
}

AdUiApp.prototype.render = function(){
	this.style = {
		"backgroundImage" : "url(" + this.icon + ")"
	};
	this.open = function(e){
		this.status = AdUiApp.status.show;
		
		var win = new WindowApp({
			data : {
				title : this.title,
				src : this.src,
				style : this.style
			}
		});
		
	}.bind(this);
}

var os = new AdUi();

/**　系统启动步骤前处理．
 *　　1.展示系统启动界面
 *　　2.加载系统需要的数据
 */
os.on( AdUi.step.BeforeStart, function(){
	this.tmp = {};
	var start = document.createElement("start");
	setStyle( start,{
		"display" : "block",
		"position" : "fixed",
		"left" : "0", "right":"0","top":"0","bottom":"0",
		"background" : "red"
	});
	this.tmp.start = start;
	document.body.appendChild(start);
	
	var int = setInterval( function(){
		( this.status == AdUi.status.running ) && ( function(){ this.tmp.start.remove(); clearInterval( int ); } ).bind(this)();
	}.bind(this),400);
	
	// 造数
//	var data = this.data = (function(){
//		var data = [] , tmpApp;
//		for( var i = 0;i < 10; i++ ){
//			tmpApp = new AdUiApp({ 
//				appid : i ,
//				title : "应用" + i,
//				icon : "./img/liulian.png",
//				src : "http://www.skjanyou.cn"
//			});
//			data.push( tmpApp );
//		}
//		
//		return data;
//	})();
	
	var bilibili = new AdUiApp({appid:'bilibili',title:"哔哩哔哩",icon:"./img/liulian.png",src:"https://www.bilibili.com/"});
	var blog = new AdUiApp({appid:'blog.skjanyou',title:"skjanyou博客网",icon:"./img/liulian.png",src:"http://blog.skjanyou.cn"});
	var jokes = new AdUiApp({appid:'jokes.skjanyou',title:"skjanyou笑话网",icon : "./img/liulian.png",src:"http://www.skjanyou.cn"});
	this.data = [ bilibili,blog,jokes ];
});


/**  系统启动步骤后处理
 * 	  1.移除系统启动界面
 *    2.其他处理 
 */
os.on( AdUi.step.AfterStart, function(){
	// 安装应用
	this.data.forEach(function( uiApp ){
		this.installApp( uiApp );
	}.bind(this));
	
	var background = document.createElement("backgound");
	
	setStyle( background, {
		"background" : "url(img/mio.jpg)",
		"position" : "fixed",
		"left" : "0",
		"top" : "0",
		"width" : "100%",
		"height" : "100%",
		"background-size" : "cover",
		"background-repeat" : "no-repeat",
		"background-position" : "center center",
		"display" : "block",
		"z-index" : "-1"
 	});
 	document.body.appendChild( background );
 	new Vue({
 		el : "adui-desktop",
 		data : {
 			apps : this.app
 		}
 	});
 	
 	new Vue({
 		el : "adui-taskbar-app",
 		data : {
 			apps : this.app
 		}
 	});
 	
 	new Vue({
 		el : "adui-taskbar-start",
 		data : {},
 		methods : {
 			quickStart : function(){
 				if( !this.$taskStart ){
	 				var taskStart = this.$taskStart = new TaskStart({
	 					data:{}
	 				});
 				}else{
 					this.$taskStart.show = !this.$taskStart.show;
 				}
 			},
 			taskView : function(){
 				console.log("taskView",this);
 			}
 		}
 	});
 	
 	document.addEventListener('contextmenu',function(e){
 		var cm = new Contextmenu({
 			data : {
				menu : [
					{ text : "全屏", callback : function(){fullScreen();}},
					{ text : "刷新", callback : function(){console.log("callback");}},
					{ 
						text : "关于", 
						callback : function(){
							new Message({
								data : {
									message : "关于作者"
								}
							});
						}
					}
				],
				style : {
					left : e.clientX +"px",
					top  : e.clientY +"px"
				}
 			}
 		});
    	if (e.cancelable) {
            // 判断默认行为是否已经被禁用
            if (!e.defaultPrevented) {
                e.preventDefault();
            }
        }
        e.stopImmediatePropagation();
        e.stopPropagation();	
 	},false);
});

os.on( AdUi.step.BeforeShutdown, function(){
	this.tmp = {};
	var shutdown = document.createElement("shutdown");
	setStyle( shutdown,{
		"display" : "block",
		"position" : "fixed",
		"left" : "0", "right":"0","top":"0","bottom":"0",
		"background" : "yellow"
	});
	this.tmp.shutdown = shutdown;
	document.body.appendChild(shutdown);	
	var int = setInterval( function(){
		( this.status == AdUi.status.shutdown ) && ( function(){ this.tmp.shutdown.remove(); clearInterval( int ); } ).bind(this)();
	}.bind(this),400);	
});

os.on( AdUi.step.AfterShutdown, function(){
	

});

os.startup();


});